package com.boot.proxy;

import org.springframework.cglib.core.DebuggingClassWriter;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Package com.boot.aop
 */
public class CglibProxy {

    //定义获取代理对象方法
    public Object getCglibProxy(Object target,Class superclass){
        Enhancer enhancer = new Enhancer();
        //设置父类,因为Cglib是针对指定的类生成一个子类，所以需要指定父类
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(new CglibInterceptor(target));// 设置回调
        Object result = enhancer.create();//创建并返回代理对象
        return result;
    }

    public static void main(String[] args) {
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\\IdeaProjects\\spring-boot-demo\\src\\test\\com\\boot\\proxy");
        CglibProxy cglib = new CglibProxy();//实例化CglibProxy对象
        UserManager user =new UserManagerImpl();
        UserManager user_proxy =  (UserManager) cglib.getCglibProxy(user,UserManagerImpl.class);//获取代理对象
        user_proxy.delUser("admin");//执行删除方法
    }

}
